package cn.louzen.utils;

import cn.louzen.domain.SampleOrg;
import cn.louzen.domain.SampleStore;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric_ca.sdk.HFCAClient;
import org.hyperledger.fabric_ca.sdk.HFCAIdentity;
import org.hyperledger.fabric_ca.sdk.exception.IdentityException;
import org.hyperledger.fabric_ca.sdk.exception.InvalidArgumentException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;

public class CAUtil {
    /**
     * 得到CAClient
     *
     * @param sampleOrg
     * @throws Exception
     */
    public static void getCAClient(SampleOrg sampleOrg) throws Exception {
        HFCAClient caClient = getCAClient(sampleOrg.getCAName(), sampleOrg.getCALocation(), sampleOrg.getCAProperties());
        sampleOrg.setCAClient(caClient);
    }

    /**
     * 得到CAClient
     *
     * @param caName
     * @param caLocation
     * @param caProperties
     * @return
     * @throws Exception
     */
    public static HFCAClient getCAClient(String caName, String caLocation, Properties caProperties)
            throws Exception {
        HFCAClient caClient;
        if (caName != null && !caName.isEmpty()) {
            // caName=ca,CALocation=http://xxxx:7054,CAProperties=null
            caClient = HFCAClient.createNewInstance(caName, caLocation, caProperties);
        } else {
            // CALocation=http://xxxx:7054,CAProperties=null
            caClient = HFCAClient.createNewInstance(caLocation, caProperties);
        }
        caClient.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
        return caClient;
    }

    public static Collection<HFCAIdentity> getHFCAIdentity(String sampleUserName,
                                                           SampleOrg sampleOrg, SampleStore sampleStore)
            throws InvalidArgumentException, IdentityException {
        Collection<HFCAIdentity> allIdentities = new ArrayList<>();
        HFCAClient caClient = sampleOrg.getCAClient();
        allIdentities = caClient.getHFCAIdentities(sampleStore.getMember(sampleUserName, sampleOrg.getName()));
        return allIdentities;
    }
}
